:- module(toc_mapping,[]).


:- use_module('../ns').
:- use_module('../lib/t_record').
:- use_module('../p2r/match').
:- use_module(library('http/http_open')).


directory(Dir,URI) :-
	t_record:t_record('toc/table_of_contents_full.tsv',[_,T]),
	atom_concat('data/',T,Dir),
	ns:item_ns(NS),
	atom_concat(NS,T,URI).

/**
 * Mapping dataset entries in the TOC
 */
match:
	(
	 ns:item_ns(NS),
	 toc_mapping:check(Id),
	 t_record:t_record('toc/table_of_contents_full.tsv',[Desc,Id,_,LastUpdate,DataStart,DataEnd,_Values,_Rows,_Cols,_]),
	 toc_mapping:parse_desc(Desc,_,Label)
	)
		eq
	[
		rdf(pattern([NS,Id]),rdf:type,riese:'Dataset')
	,	rdf(pattern([NS,Id]),dc:title,literal(Label))
	,	rdf(pattern([NS,Id]),rdfs:label,literal(Label))
	,	rdf(pattern([NS,Id]),riese:last_update,literal(LastUpdate))
	,	rdf(pattern([NS,Id]),riese:data_start,literal(DataStart))
	,	rdf(pattern([NS,Id]),riese:data_end,literal(DataEnd))
	].

/**
 * Access type
 */
match:
	(
	 ns:item_ns(NS),
	 toc_mapping:check(Id),
	 t_record:t_record('toc/table_of_contents_full.tsv',[_,Id,dataset,_,_,_,_,_,_,restricted])
	)
		eq
	[
		rdf(pattern([NS,Id]),riese:access_type,literal(restricted)) %hmm...
	].
	

/**
 * Mapping hierarchy to SKOS
 */
match:
        (
         ns:item_ns(NS),
         toc_mapping:(check(Id1),check(Id2)), %hack, but saves an awful lot of time
	 toc_mapping:sub_id(Id1,Id2)
	)
                eq
        [
                rdf(pattern([NS,Id1]),skos:narrower,pattern([NS,Id2]))
	,	rdf(pattern([NS,Id2]),skos:broader,pattern([NS,Id1]))
        ].


check(Id) :-
	atomic(Id),!,
	concat_atom([_],'/',Id).
check(_).

%TOCNS hasTopConcept /data/

parse_desc(Desc,N,Label) :-
	atom_chars(Desc,D),append(L,[Z|R],D),Z\=' ',length(L,N),forall(member(M,L),M=' '),
	atom_chars(Label,[Z|R]).


	
sub_id(Id,Id2) :-
	level_list(Levels),
	level(Id,_L1),
	extract(Id,Levels,Sub),
	member(level(Id2,_L2),Sub).

extract(_,[],[]).
extract(Id,[level(Id,L)|T1],T2) :-
	!,extract_in(Id,L,T1,T2).
extract(Id,[_|T1],T2) :-
	extract(Id,T1,T2).
extract_in(_,_,[],[]).
extract_in(Id,L,[level(_,SL)|T1],T2) :-
	SL < L+1,!,
	extract(Id,T1,T2).
extract_in(Id,L,[level(_,SL)|T1],T2) :-
	SL > L+1,!,
	extract_in(Id,L,T1,T2).
extract_in(Id,L,[level(SId,SL)|T1],[level(SId,SL)|T2]) :-
	extract_in(Id,L,T1,T2).





level(Id,M) :-
	t_record:t_record('toc/table_of_contents_full.tsv',[Desc,Id]),
	parse_desc(Desc,N,_),
	M is N/4.

:- dynamic levels/1.
% parse on first time
level_list(Levels) :- levels(Levels),!.
level_list(Levels) :- 
	findall(level(Id,L),toc_mapping:level(Id,L),Levels),
	assert(levels(Levels)).


